package com.lianjing.sh.acceleo.controller.tool.query;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.uml2.uml.Property;

import com.lianjing.sh.acceleo.controller.tool.service.NameService;

public class Property_Common {
	
	private final NameService nameService = new NameService();
	
	/**
	 * 没有分组标识的属性会被单独分组
	 */
	public List<List<Property>> group(List<Property> ps){
		List<List<Property>> newPs = new ArrayList<>();
		List<Property> list = new ArrayList<>();
		boolean flag = false;
		for(Property p : ps){
			if(!flag && nameService.isNameGroupStart(p)){
				flag=true;
			}
			if(flag && nameService.isNameGroupEnd(p)){
				flag=false;
			}
			list.add(p);
			if(!flag){
				newPs.add(list);
				list = new ArrayList<>();
			}
		}
		return newPs;
	}
	
	/**
	 * 只含有分组标识的属性
	 */
	public List<List<Property>> groupOnly(List<Property> ps){
		List<List<Property>> newPs = new ArrayList<>();
		List<Property> list = new ArrayList<>();
		boolean flag = false;
		for(Property p : ps){
			if(!flag && nameService.isNameGroupStart(p)){
				flag=true;
			}
			if(flag && nameService.isNameGroupEnd(p)){
				list.add(p);
				flag=false;
			}
			if(flag){
				list.add(p);
			}
			if(!flag){
				if(!list.isEmpty()){
					newPs.add(list);
				}
				list = new ArrayList<>();
			}
		}
		return newPs;
	}
	
	public List<Property> uniqueByName(List<Property> ps){
		Map<String, Property> map = new LinkedHashMap<>();
		for(Property p : ps){
			String name = nameService.getSimpleName(p);
			if(!map.containsKey(name)){
				map.put(name, p);
			}
		}
		return new ArrayList<>(map.values());
	}
	
}
